package demo.maven.bean.singleton;

/**
 * 同步延迟加载 — 使用Threadlocal实现延迟加载
 * 饥饿和懒汉的结合
 * @author peter
 * @date 2022/2/24 下午16:25
 */
public class Singleton6 {
    private static ThreadLocal<Singleton6> threadLocal = new ThreadLocal<Singleton6>();

    private static Singleton6 instance  = null;

    private Singleton6(){}

    public static Singleton6 getInstance() {

        // 第一次检查，该线程是否第一次访问
        if (threadLocal.get() == null) {
            synchronized (Singleton6.class) {
                if (instance == null) {
                    instance = new Singleton6();
                }
            }
            threadLocal.set(instance);
        }
        return instance;
    }
}
